import { useRoute } from "vue-router";
import { ref, computed } from "vue";
import { useLocalStorage } from "@vueuse/core";
import { showToast } from "@/utils/toastHelper";
import { useRouter } from "vue-router";

export function useMemoEdit() {
  const route = useRoute();
  const router = useRouter();

  const id = route.params.id;
  const memoList = useLocalStorage("memo-list", []);

  const currentMemoList = computed(() => {
    return memoList.value.find(
      (item) => Number(item.id) === Number(route.params.id)
    );
  });

  const title = ref(currentMemoList.value?.title || "");
  const body = ref(currentMemoList.value?.body || "");

  function updateMemo() {
    memoList.value = memoList.value.map((item) => {
      if (Number(item.id) === Number(id)) {
        return {
          ...item, //拿过来，然后只更新title和body
          title: title.value,
          body: body.value,
        };
      }
      return item;
    });
    showToast("更新成功");
    router.push("/memo");
  }
  return {
    title,
    body,
    updateMemo,
  }

}
